﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ScFramework.Core
{

    public class UserManager : SystemModule,INeedRemove
    {
        public bool IsHost
        {
            get => _main.TempUserID == 1;
        }
        Dictionary<int,UserState> _userState = new Dictionary<int, UserState>();

        Dictionary<Tuple<UserState, UserState>, UserStateAcionPair> userActionDic = new Dictionary<Tuple<UserState, UserState>, UserStateAcionPair>();
        public UserState GetUserState(int id)
        {
            if (_userState.ContainsKey(id) == false)
            {
                _userState[id] = UserState.Null;
            }
            return _userState[id];
        }
        public void SetUserState(int id,UserState state)
        {
            if (IsHost == false)
            {
                return;
            }
            if (GetUserState(id) == state)
            {
                return;
            }
            else
            {
                if (userActionDic.ContainsKey(new Tuple<UserState, UserState>(GetUserState(id), state)))
                    userActionDic[new Tuple<UserState, UserState>(GetUserState(id), state)].DoActon(id);
                _userState[id] = state;
            }
        }
        public void RegisterUserEvent(Action<int> action,UserState lst,UserState nxt,int order=0)
        {
            var key = new Tuple<UserState, UserState>(lst, nxt);
            if (userActionDic.ContainsKey(key) == false)
            {
                userActionDic[key] = new UserStateAcionPair();
            }
            userActionDic[key].Add(action, order);
        }
        public void RemoveAbout(object obj)
        {
            foreach(var x in userActionDic.Values)
            {
                x.Remove(obj);
            }
        }
        /// <summary>
        /// 0:无用户
        /// 1:host
        /// 2...:guest
        /// </summary>
        public int UserID
        {
            get => _main.TempUserID;
        }
        public override void Update(float deltaTime)
        {
            base.Update(deltaTime);
            //Debug.Log(GetUserState(UserID));
        }
    }
    public class UserStateAcionPair
    {
        public UserStateAcionPair() { }
        List<Tuple<int, Action<int>>> Actions = new List<Tuple<int, Action<int>>>();
        public void DoActon(int id)
        {
            Actions.Sort();
            foreach(var x in Actions)
            {
                x.Item2(id);
            }
        }
        public void Add(Action<int> act,int order)
        {
            Actions.Add(new Tuple<int, Action<int>>(order,act));
        }
        public void Remove(object obj)
        {
            Actions.RemoveAll(s => s.Item2.Target == obj);
        }
    }
    public enum UserState
    {
        Null,
        OnCombine,
        OnGame
    }

}